<?php
namespace app\admin\controller;

use app\admin\tool\Parser;
use app\common\model\Template as TemplateModel;
use think\Loader;
use think\Request;

class Template extends Base{

    public function index(){

        $template = TemplateModel::where([])->order('id desc')->paginate(10);

        $this->data['model'] = $template;
        $this->data['title']  = '模板列表';
        $this->data['parser'] = new Parser();
        $this->data['column'] = $this->column();

        return view('',$this->data);
    }


    public function add(){

        $this->data['title'] = '模板添加';

        return view('',$this->data);
    }

    public function edit(){

        $this->data['title'] = '模板编辑';

        return view('',$this->data);
    }

    public function create(Request $request){
        $data = $request->post();

        $validate = Loader::validate('Template');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['add_time'] = $data['update_time'] = time();

        $model = new TemplateModel();
        $model->data($data);
        if($model->allowField(true)->save()){
            $this->success("新增成功");
        }

        $this->error("操作失败");
    }

    public function update(Request $request){
        $data = $request->post();
        if(empty($data['id'])){
            $this->error("操作失败");
        }

        $validate = Loader::validate('Template');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        $data['update_time'] = time();

        $model = new TemplateModel();
        if($model ->allowField(true)-> save($data,['id'=>$data['id']])){
            $this->success("更新成功");
        }

        $this->error("操作失败");
    }


    /**
     * 给其他的模块调用模板模块使用
     */
    public function lists(){

        $template = TemplateModel::where([])->order('add_time desc')->paginate(10);

        $this->data['model'] = $template;
        $this->data['title'] = '模板列表';
        $this->data['column'] = $this->column();
        $this->data['parser'] = new Parser();

        return view('',$this->data);
    }


    /**
     * @param Request $request
     */
    public function getTemplate(Request $request){
        $id = $request->param('id');
        $template = TemplateModel::get($id);
        $this->success('获取成功','',$template);
    }

    protected function column(){
        return [
            'title'      =>['name'=>'模板标题','fun'=>'text','options'=>[]],
            'desc'       =>['name'=>'模板描述','fun'=>'text','options'=>[]],
            'path'       =>['name'=>'模板路径','fun'=>'text','options'=>[]],
            'add_time'   =>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d H:i']],
            'update_time'=>['name'=>'更新时间','fun'=>'text','options'=>[]],
        ];
    }
}